
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView

# 导入SDK依赖包QQLoginTool中的方法
from QQLoginTool.QQtool import OAuthQQ

# 导入配置文件，可获取配置文件中信息
from django.conf import settings

# 导入qq登陆用户模型类
from oauth.models import OAuthQQUser

# 导入token-jwt
from rest_framework_jwt.settings import api_settings

# 导入加密模块
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS

# 导入序列化器
from oauth.serializers import OauthSerializer


class Get_QQ_Code(APIView):
    def get(self,request):
        state = request.query_params.get('next')
        if state is None:
            state = '/'
        # 创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state=state)

        # 获取QQ登录扫码页面，扫码后得到Authorization Code
        login_url = oauth.get_qq_url()

        # 3、返回url
        return Response({'login_url': login_url})


class Get_QQ_OpenID(CreateAPIView):

    serializer_class = OauthSerializer

    def get(self,request):
        code = request.query_params.get("code")
        if code is None:
            return Response({"error":"获取code失败"}, status=400)
        else:
            oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI,state="/")
        # 通过AuthorizationCode获取Access_Token
        access_token = oauth.get_access_token(code)
        # 通过AccessToken获取OpenID
        openid = oauth.get_open_id(access_token)
        try:
            user_openid = OAuthQQUser.objects.get(openid=openid)
        except:
            # 创建加密对象（秘钥，时限）
            tjwss = TJWSS(settings.SECRET_KEY, 300)
            # 加密数据
            openid_ok = tjwss.dumps(openid).decode()

            return Response({"access_token":openid_ok})

        else:

            user = user_openid.user
            # 生成jwt token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            data = {
                "user_id":user.id,
                "username":user.username,
                "token":token
            }
            return Response(data=data)